package com.cqtczh.qhd.driver.acticity;

import httptools.HttpJsonTool;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javabeen.DriverOrderCountBeen;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import tools.L;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;


import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;

import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.slidingmenu.lib.SlidingMenu;
import com.cqtczh.qhd.driver.AppContent;
import com.cqtczh.qhd.driver.R;
import com.cqtczh.qhd.driver.AppContent.GetGpsAddress;
import com.cqtczh.qhd.driver.AppContent.GetPushMessage;
import com.cqtczh.qhd.driver.acticity.base.BaseActivity;
import com.cqtczh.qhd.driver.acticity.user.IntentionAddress;
import com.cqtczh.qhd.driver.acticity.user.MessageActivity;
import com.cqtczh.qhd.driver.acticity.user.UserLoginActivity;
import com.cqtczh.qhd.driver.api.GagApi;
import com.cqtczh.qhd.driver.model.CargoInfo;
import com.cqtczh.qhd.driver.model.DownLoadAPP;
import com.cqtczh.qhd.driver.model.Driver;
import com.cqtczh.qhd.driver.model.Message;
import com.cqtczh.qhd.driver.model.OffLineData;
import com.cqtczh.qhd.driver.utils.Base64Util;
import com.cqtczh.qhd.driver.utils.SPUtils;
import com.cqtczh.qhd.driver.utils.StringUtils;
import com.cqtczh.qhd.driver.vo.JsonRequest;
import com.cqtczh.qhd.driver.vo.JsonResponse;
import com.cqtczh.qhd.driver.vo.State;

/**
 * * @author 作者 陈修园:
 * 
 * @date 创建时间：2015-5-5 下午7:41:34
 * @version 1.0
 * @parameter
 * @since
 * @return
 */
public class new_home_activity extends BaseActivity implements OnClickListener {
	private TextView user_gps;
	private ImageView user_info_tou;
	private ImageView Start_Work, work_image;
	private Driver user;
	private LocationClient mLocationClient;
	private LocationMode tempMode = LocationMode.Hight_Accuracy;
	private String tempcoor = "bd09ll";
	public Vibrator mVibrator;

	private int baiduCheckCurrt=10;
	
	/**
	 * 司机完成的订单信息
	 */
	private List<DriverOrderCountBeen> driverOrderCountBee;

	public LinearLayout gps_ban;

	private RequestParams params;

	public static Gson gson = new Gson();

	private HttpUtils http = new HttpUtils();

	private AppContent app;

	private PreferencesCookieStore preferencesCookieStore;

	private String key = "UserInfo";

	// private ListViewForScrollView UnCompleteOrderList;
	/**
	 * 新版本不要这个了暂时
	 */
	// private ListView UnCompleteOrderList;

	private BitmapUtils bUtils;

	private boolean Is_Work_Flag = false;

	private RotateAnimation work_image_animation;

	private List<CargoInfo> sourceDateList;

	private List<Message> messages;

	private List<String> CarTeamRequest = new ArrayList<String>();

	private List<Map<String, Object>> get_data;

	private boolean Refreash = false;

	private SimpleAdapter adapter;

	private LinearLayout moveTouch;

	// 跟随互动的控件
	private View button_View;

	// 滑动控件的上部分
	private int moveTouch_TopY;

	// 滑动控件的下部分
	private int moveTouch_BouttonY;
	// 跟随滑动的控件是底部
	private int moveButtonView_buttonY;
	// 跟随互动的控件顶部
	private int moveButtonView_TopY;

	private int display_Y;

	private int display_X;

	private GestureDetector mGestureDetector;

	private boolean flag = false;
	private float lostMoveY;
	/**
	 * 设置返空车
	 */
	private Button setAddress;
	/**
	 * 侧滑菜单的名字
	 */
	private TextView menu_Name;
	private View menu_integral, menu_place, account, shop, change, update,
			serve, introduce, deal, menu_esc, menu_night;
	private TextView head_title;
	private Context context;
	private ImageView head_left;
	private SlidingMenu menu;

	/**
	 * 司机在线或者不在线
	 */
	private TextView showdriverstae;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_new_home_v2);
		// L.v("new_home_activity", "new_home_activity");
		bUtils = new BitmapUtils(this);
		app = (AppContent) getApplication();
		setAddress=(Button) findViewById(R.id.setAddress);
		Ini();
		baidulbs();
		// getUserInfo();
		GetGPSLocation();
		// CheckResh();
		// SetMoveTouch();
		// SetOrderNumber();
		GetRequestMessage();
		getUnCompleteOrder();
		OnListenerPushMessage();
		//获得个推的clind
//		L.e("获得个推的clind", "个推的的clind---》"+PushManager.getInstance().getClientid(getApplicationContext()));

	}

	@SuppressWarnings("deprecation")
	private void Ini() {
		// mGestureDetector=new GestureDetector(new TouchMoveAction(this));
		// moveTouch = (LinearLayout) findViewById(R.id.touchMove);
		// button_View = findViewById(R.id.button_View);
		// 获得屏幕的高度
		DisplayMetrics locaDisplayMetrics = new DisplayMetrics();
		WindowManager mWm = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		mWm.getDefaultDisplay().getMetrics(locaDisplayMetrics);
		display_Y = locaDisplayMetrics.heightPixels;
		display_X = locaDisplayMetrics.widthPixels;
		// 获得屏幕的高度
		user_gps = (TextView) findViewById(R.id.Gps_TextView);
		// user_gps.setOnClickListener(new_home_activity.this);
		// user_gps.setOnClickListener(this);
		user_gps.setText(app.adrr);
		preferencesCookieStore = AppContent.getPreferencesCookieStore();
		this.getSharedPreferences(key, Context.MODE_PRIVATE);
		gps_ban = (LinearLayout) findViewById(R.id.gps_ban);
		gps_ban.setOnClickListener(this);
		Start_Work = (ImageView) findViewById(R.id.background);
		Start_Work.setOnClickListener(this);
		ImageView s_log_1 = (ImageView) findViewById(R.id.workstart);
		s_log_1.setOnClickListener(this);
		work_image = (ImageView) findViewById(R.id.workstart);
		// work_image.setBackgroundResource(R.drawable.start);
		// work_info=(TextView) findViewById(R.id.isWork);
		work_image_animation = (RotateAnimation) AnimationUtils.loadAnimation(
				this, R.anim.rotating);
		LinearInterpolator lir = new LinearInterpolator();
		work_image_animation.setInterpolator(lir);
		work_image_animation.setInterpolator(lir);
		// UnCompleteOrderList = (ListViewForScrollView)
		// findViewById(R.id.order_listView);
		// UnCompleteOrderList = (ListView) findViewById(R.id.order_listView);
		// SetOrderNumber();
		sourceDateList = new ArrayList<CargoInfo>();
		get_data = new ArrayList<Map<String, Object>>();
		// SetMoveTouch();
		iniMenu();
		showdriverstae = (TextView) findViewById(R.id.showdriverstae);
		setAddress.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				openActivity(IntentionAddress.class);
			}
		});
	}

	private void iniMenu() {
		head_left = (ImageView) findViewById(R.id.head_left);
		head_left.setImageResource(R.drawable.menu);
		head_left.setVisibility(0);
		TextView title=(TextView) findViewById(R.id.head_title);
		title.setText("Q货的");
		head_left.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				L.v("出来了", "出来了");

				app.menuCEHDonChange();

				// 显示SlidingMenu
				// menu.showContent();

			}
		});
	}

	private void baidulbs() {

		mLocationClient = ((AppContent) getApplication()).mLocationClient;
		InitLocation();
		mLocationClient.start();

	}

	private void InitLocation() {
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(tempMode);// 设置定位模式
		option.setCoorType(tempcoor);// 返回的定位结果是百度经纬度，默认值gcj02
		int span = AppContent.LOCATION_TIME;
		option.setScanSpan(span);// 设置发起定位请求的间隔时间为5000ms
		option.setIsNeedAddress(true);
		mLocationClient.setLocOption(option);
	}

	// 获得Gps的地址
	public void GetGPSLocation() {
		// L.v("GetGPSLocation", "GetGPSLocation");
		app.GetGpsAddressCallBack(new GetGpsAddress() {

			@Override
			public void GetAddress(String address) {
				// TODO Auto-generated method stub
				L.v("测试", "测试");
				user_gps.setText(address);
			}
		});
		// user_gps
		if (baiduCheckCurrt==0) {
			checkBaiduPushMessageEable();
		}else {
			baiduCheckCurrt--;
		}
		
	}

	
	/**
	 * 
	* @Title: checkBaiduPushMessageEable 
	* @Description: TODO(检查百度推送是否开启) 
	* @param   参数说明 
	* @return void    返回类型 
	* @throws
	 */

	private void checkBaiduPushMessageEable(){
		
	}
	
	
	private void getUnCompleteOrder() {
		//Type types=new TypeToken<List<CarTypeBeen>>(){}.getType();
		L.v("getUnCompleteOrder", "getUnCompleteOrder");
		HashMap<String, String> dataMap = new HashMap<String, String>();
		if (app.userId == null || app.userId.length() <= 0) {
			openActivity(UserLoginActivity.class);
			this.finish();
			return;
		}
		dataMap.put("carownerid", app.userId);
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler(){
			@Override
			public void handleMessage(android.os.Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
			//	L.v("点击到了", "点击到了");
				if (msg.what==1) {
				//	L.v("点击到了", "点击到了");
					driverOrderCountBee = (List<DriverOrderCountBeen>) msg.obj;
					serDeriverOrderInfo();
				}
			}
		});
		Type type = new TypeToken<List<DriverOrderCountBeen>>() {
		}.getType();
		httpJsonTool.StartWork(dataMap, GagApi.GET_ORDER_COUNT, type, null);

	}

	public void serDeriverOrderInfo() {
		if (driverOrderCountBee.size()>0) {
			L.v("serDeriverOrderInfo", "serDeriverOrderInfo->"+driverOrderCountBee.size());
			TextView ordTextView = (TextView) findViewById(R.id.ordTextView);
			ordTextView.setText(driverOrderCountBee.get(0).getOrderCount() + "");
			TextView order_Money = (TextView) findViewById(R.id.order_Money);
			order_Money.setText(driverOrderCountBee.get(0).getSumPrice() + "");
		}else {
			//L.v("没有获得数据", "没有获得数据");
		}
		
	}

	// private void getUnCompleteOrder() {
	// // showLoadingDialog("数据载入中...");
	// L.v("-------getUnCompleteOrder---------",
	// "----------getUnCompleteOrder----------------");
	// Map<String, Object> dataMap = new HashMap<String, Object>();
	// HttpUtils http = new HttpUtils();
	// String flowStatus = "1";
	// dataMap.put("flowStatus", flowStatus);
	// dataMap.put("driverPhone", app.user_phone_no);
	// JsonRequest jr = JsonRequest.getInit();
	// jr.setData(dataMap);
	// String json = gson.toJson(jr);
	// RequestParams params = new RequestParams();
	// params.addBodyParameter("jsonParam", json);
	// http.configCookieStore(AppContent.getPreferencesCookieStore());
	// http.send(HttpRequest.HttpMethod.POST, GagApi.GETPLANLIST, params,
	// new RequestCallBack<String>() {
	//
	// @Override
	// public void onSuccess(ResponseInfo<String> responseInfo) {
	// L.v("------getUnCompleteOrder-2---------",
	// "---------getUnCompleteOrder-----2------------");
	// // dismissLoadingDialog();
	// System.out.println("进入添加订单lists");
	// // System.out.println("list:" + responseInfo.result);
	// Gson gson2 = new Gson();
	// JsonResponse jrs = gson2.fromJson(responseInfo.result,
	// JsonResponse.class);
	// State state = jrs.getState();
	//
	// // System.out.println(preferencesCookieStore);
	// if (state.getCode().equals(State.SUCEECCODE)) {
	//
	// // 存用户登录信息
	// // System.out.println(responseInfo.result);
	// // System.out.println("进来了");
	// // System.out.println(jrs.getParam("rows") + "");
	// Type type = new TypeToken<List<CargoInfo>>() {
	// }.getType();
	// try {
	//
	// List<CargoInfo> date = gson2.fromJson(
	// new JSONObject(responseInfo.result)
	// .getJSONObject("data")
	// .getJSONArray("rows")
	// + "", type);
	// L.v("getUnCompleteOrder2",
	// "getUnCompleteOrder2");
	// for (int i = 0; i < date.size(); i++) {
	// sourceDateList.add(date.get(i));
	// }
	// ListViewContel();
	//
	// } catch (JsonSyntaxException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// } catch (JSONException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// } else {
	// System.out.println(state.getMsg());
	// if (state.getCode().equals(State.UNLOGIN)) {
	// openActivity(UserLoginActivity.class);
	// finish();
	// }
	// }
	// // ToastUtils.showLong(state.getMsg());}
	//
	// }
	//
	// @Override
	// public void onFailure(HttpException error, String msg) {
	// // testTextView.setText(error.getExceptionCode() + ":" +
	// // msg);
	// dismissLoadingDialog();
	// System.out.println(msg);
	// Toast.makeText(new_home_activity.this, msg,
	// Toast.LENGTH_LONG).show();
	// }
	// });
	//
	// }

	private void SetDataToListView() {
		get_data.clear();
		GetData();
		// L.v("data的长度", data.size() + "");
		// UnCompleteOrderList listView;
		// listView
		adapter = new SimpleAdapter(this, get_data,
				R.layout.activity_myorder_conent, new String[] {
						"myorder_content_flowid", "myorder_content_tab",
						"myorder_content_time", "myorder_content_mtext",
						"myorder_content_rmb", "myorder_content_qitext",
						"myorder_content_zhongtext" }, new int[] {
						R.id.myorder_content_flowid, R.id.myorder_content_tab,
						R.id.myorder_content_time, R.id.myorder_content_mtext,
						R.id.myorder_content_rmb, R.id.myorder_content_qitext,
						R.id.myorder_content_zhongtext });
		// UnCompleteOrderList.setAdapter(adapter);
		// UnCompleteOrderList.setOnItemClickListener(new ListViewOnItemClick()
		// {
		// @Override
		// public void OnClick(ViewGroup parent, View view, int position,
		// Object o) {
		// // TODO Auto-generated method stub
		// Map<String, Object> map = new HashMap<String, Object>();
		// map = get_data.get(position);
		// Bundle bundle = new Bundle();
		// bundle.putString("listid", map.get("myorder_content_flowid")
		// + "");
		// bundle.putString("State", "1");
		// openActivity(OrderDetails.class, bundle);
		// }
		// });
	}

	// 数据转换将JSON获得的CargoInfo变成listmap
	private void GetData() {
		// List<Map<String, Object>> list = new ArrayList<Map<String,
		// Object>>();
		for (CargoInfo goods : sourceDateList) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("myorder_content_flowid", goods.getFlowId());
			System.out.println("goods.getFlowId()" + goods.getFlowId());
			map.put("myorder_content_tab", "订单号:" + goods.getFlowId());
			// map.put("myorder_content_time", "2015 b0903");
			map.put("myorder_content_time", "发布时间:" + goods.getCreateTime());
			// System.out.println(goods.getCreateTime());
			map.put("myorder_content_mtext", goods.getDistance());
			map.put("myorder_content_rmb", goods.getTransPrice());
			map.put("myorder_content_qitext", goods.getReAddress());
			map.put("myorder_content_zhongtext", goods.getSdAddress());
			get_data.add(map);
		}
		// return list;
	}

	//

	// private void

	private void getUserInfo() {
		// System.out.println("进入getUserInfo");
		Map<String, Object> dataMap = new HashMap<String, Object>();
		JsonRequest jr = JsonRequest.getInit();
		jr.setData(dataMap);

		String json = gson.toJson(jr);
		params = new RequestParams();
		params.addBodyParameter("jsonParam", json);
		http.configCookieStore(preferencesCookieStore);
		http.send(HttpRequest.HttpMethod.POST, GagApi.DRIVERINFO, params,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						// L.v("responseInfo.result-->", responseInfo.result);
						// System.out.println("获取用户信息");
						Gson gson2 = new Gson();
						JsonResponse jrs = gson2.fromJson(responseInfo.result,
								JsonResponse.class);
						// System.out.println(responseInfo.result);
						State state = jrs.getState();
						// System.out.println(preferencesCookieStore);
						if (state.getCode().equals(State.SUCEECCODE)) {
							// 存用户登录信息
							try {
								/*
								 * app.userId = new
								 * JSONObject(responseInfo.result)
								 * .getJSONObject("data")
								 * .getJSONObject("rows").getString("driverId");
								 */
								user = gson2.fromJson(
										new JSONObject(responseInfo.result)
												.getJSONObject("data")
												.getJSONArray("rows")
												.getJSONObject(0)
												+ "", Driver.class);
								// System.out.println("appid" + app.userId);

							} catch (JsonSyntaxException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							if (user != null) {
								app.userId = user.getDriverId();
								// SetOrderNumber();
//								GetRequestMessage();
								getUnCompleteOrder();
								OnListenerPushMessage();
								try {
									CheckVersion();
								} catch (NameNotFoundException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								// System.out.println("name:"
								// + user.getDriverName());
								// user_name.setText(user.getDriverName());
								// user_phone.setText(user.getDriverMobile());
								if (!StringUtils.isEmpty(user
										.getDriverHeadImg()))
									bUtils.display(
											user_info_tou,
											GagApi.SOURCEADRR
													+ user.getDriverHeadImg());

							}

						} else {
							String nameString = (String) SPUtils.get(
									new_home_activity.this, "driverMobile", "");
							String passwordString = (String) SPUtils.get(
									new_home_activity.this, "driverPassword",
									"");
							if (!(nameString.equals(""))
									&& passwordString.equals("")){
						//		login(nameString,
						//				Base64Util.fromHex(passwordString));
							}
							else {
								openActivity(UserLoginActivity.class);
								finish();
							}
							// System.out.println(state.getMsg());
						}
						// ToastUtils.showLong(state.getMsg());

					}

					@Override
					public void onFailure(HttpException error, String msg) {
						// testTextView.setText(error.getExceptionCode() + ":" +
						// msg);
						// System.out.println(msg);
					}
				});

	}

	private void GetRequestMessage() {
		// app=(AppContent) getApplication();
		preferencesCookieStore = AppContent.getPreferencesCookieStore();

		HttpUtils httpUtils = new HttpUtils();
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("driverId", app.userId);
		JsonRequest request = JsonRequest.getInit();
		request.setData(data);
		Gson gson = new Gson();
		String json = gson.toJson(request);
		RequestParams params = new RequestParams();
		params.addBodyParameter("jsonParam", json);
		httpUtils.configCookieStore(preferencesCookieStore);
		httpUtils.send(HttpMethod.POST, GagApi.GetCarTeamRequestMessage,
				params, new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onSuccess(ResponseInfo<String> response) {
						// TODO Auto-generated method stub
						 L.v("SetOrderNumber", response.result);
						Gson responjson = new Gson();
						JsonResponse jsresponse = responjson.fromJson(
								response.result, JsonResponse.class);
						State state = jsresponse.getState();

						if (state.getCode().equals(State.SUCEECCODE)) {
							// L.v("----------------------",
							// "------------------------");
							try {
								Type type = new TypeToken<List<Message>>() {
								}.getType();
								messages = responjson.fromJson(new JSONObject(
										response.result).getJSONObject("data")
										.getJSONArray("rows")
										+ "", type);
								if (messages.size() > 0) {

									LayoutInflater inflater = LayoutInflater
											.from(new_home_activity.this);
									LinearLayout layout = (LinearLayout) inflater
											.inflate(R.layout.alert_dialog,
													null);
									final Dialog isExit = new AlertDialog.Builder(
											new_home_activity.this).create();
									isExit.show();
									isExit.setContentView(layout);
									// 设置对话框标题
									TextView title = (TextView) layout
											.findViewById(R.id.title);
									TextView message = (TextView) layout
											.findViewById(R.id.message);
									title.setText("消息提醒");
									// 设置对话框消息
									message.setText("您有新的信息，请注意查看");
									Button check = (Button) layout
											.findViewById(R.id.check);
									Button giveup = (Button) layout
											.findViewById(R.id.giveup);
									check.setText("查看");
									giveup.setText("忽略");
									check.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
//											Intent intent = new Intent(
//													new_home_activity.this,
//													ListCarTeamRequestInfo.class);
//											intent.putExtra("ListMessage",
//													(Serializable) messages);
//											startActivity(intent);
//											isExit.dismiss();
										}
									});
									giveup.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											isExit.dismiss();
										}
									});
								}
							} catch (Exception e) {
								// TODO: handle exception
							}
						}
					}
				});

	}

	private void CheckVersion() throws NameNotFoundException {
		// int verCode =
		// this.getPackageManager().getPackageInfo(getPackageName(),
		// 0).versionCode;
		// System.out.println("版本号：" + verCode);
		try {
			int verCode = this.getPackageManager().getPackageInfo(
					getPackageName(), 0).versionCode;
			Map<String, Object> dataMap = new HashMap<String, Object>();
			JsonRequest jr = JsonRequest.getInit();
			dataMap.put("versionNumber", verCode + "");
			dataMap.put("versionType", "司机版本");
			jr.setData(dataMap);
			final Gson gson = new Gson();
			String json = gson.toJson(jr);
			// System.out.println(json);
			HttpUtils http = new HttpUtils();
			RequestParams params = new RequestParams();
			params.addBodyParameter("jsonParam", json);
			http.send(HttpRequest.HttpMethod.POST, GagApi.CheckVersion, params,
					new RequestCallBack<String>() {

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							// testTextView.setText("reply: " +
							// responseInfo.result);
							JsonResponse jrs = gson.fromJson(
									responseInfo.result, JsonResponse.class);
							// System.out.println("升级 + " +
							// responseInfo.result);
							State state = jrs.getState();
							// L.v("去更新1","去更新");
							if (state.getCode().equals(State.SUCEECCODE)) {
								// L.v("去更新2","去更新");
								if (GagApi.UPAPKPATH != null) {

									// 创建退出对话框
									LayoutInflater inflater = LayoutInflater
											.from(new_home_activity.this);
									LinearLayout layout = (LinearLayout) inflater
											.inflate(R.layout.alert_dialog,
													null);
									final Dialog isExit = new AlertDialog.Builder(
											new_home_activity.this).create();
									isExit.show();
									isExit.setContentView(layout);
									// 设置对话框标题
									TextView title = (TextView) layout
											.findViewById(R.id.title);
									TextView message = (TextView) layout
											.findViewById(R.id.message);
									title.setText("消息提醒");
									// 设置对话框消息
									message.setText("有新的版本更新");
									Button check = (Button) layout
											.findViewById(R.id.check);
									Button giveup = (Button) layout
											.findViewById(R.id.giveup);
									check.setText("下载");
									giveup.setText("忽略");
									check.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											Intent intents = new Intent();
											intents.setClass(
													new_home_activity.this,
													DownLoadAPP.class);
											startService(intents);
											isExit.dismiss();
										}
									});
									giveup.setOnClickListener(new OnClickListener() {

										@Override
										public void onClick(View arg0) {
											// TODO Auto-generated method stub
											isExit.dismiss();
										}
									});

									// UpdateManager uManager = new
									// UpdateManager(
									// new_home_activity.this);
									// uManager.apkUrl = GagApi.UPAPKPATH;
									// uManager.checkUpdateInfo();
								} else {
									System.out.println("已经是最新的版本");
									//
								}
								// findXq();

							} else {
								// System.out.println(state.getMsg());
								// ToastUtils.showLong(state.getMsg());
							}
						}

						public void onFailure(HttpException error, String msg) {
							// System.out.println(msg);
						}
					});
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void login(String name, String sd,String password) {

		Map<String, Object> dataMap = new HashMap<String, Object>();
		JsonRequest jr = JsonRequest.getInit();
		dataMap.put("driverMobile", name);
		dataMap.put("driverPassword", password);
		System.out.println("-UUU------"
				+ (String) SPUtils.get(new_home_activity.this, "driverMobile",
						"333")
				+ (String) (SPUtils.get(new_home_activity.this,
						"driverPassword", ""))
				+ Base64Util.fromHex(""
						+ SPUtils.get(new_home_activity.this, "driverPassword",
								"biubiu")));
		jr.setData(dataMap);
		String json = gson.toJson(jr);
		params = new RequestParams();
		params.addBodyParameter("jsonParam", json);
		// http.configCookieStore(preferencesCookieStore);
		http.send(HttpRequest.HttpMethod.POST, GagApi.LOGIN, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						// testTextView.setText("conn...");
						showLoadingDialog("验证账户中，请稍等...");
					}

					@Override
					public void onLoading(long total, long current,
							boolean isUploading) {
						if (isUploading) {

						} else {

						}
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						dismissLoadingDialog();
						JsonResponse jrs = gson.fromJson(responseInfo.result,
								JsonResponse.class);
						System.out.println(responseInfo.result);
						State state = jrs.getState();
						if (state.getCode().equals(State.SUCEECCODE)) {
							// 存用户登录信息
							/*
							 * editor = share.edit(); editor.putString("Token",
							 * state.getToken()); editor.putString("driverId",
							 * jrs.getParam("driverId")+""); editor.commit();
							 */
							// System.out.println("登录存储的TOken："+state.getToken());

							DefaultHttpClient httpClient = (DefaultHttpClient) http
									.getHttpClient();
							List<Cookie> cookies = httpClient.getCookieStore()
									.getCookies();
							for (int i = 0; i < cookies.size(); i++) {
								Cookie cookie = cookies.get(i);
								// System.out.println(cookie);
								AppContent.getPreferencesCookieStore()
										.addCookie(cookie);
							}
							AppContent
									.setPreferencesCookieStore(preferencesCookieStore);
							// getUserInfo();
							// System.out.println("login:"
							// + AppContent.getPreferencesCookieStore()
							// .getCookie("JSESSIONID"));
						//	getUserInfo();

						} else {
							// System.out.println(state.getMsg());
							showLongToast(state.getMsg());
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						dismissLoadingDialog();
					}
				});
	}

	private void ListViewContel() {
		if (Refreash) {
			L.v("ListViewContel", "Refreash" + Refreash);
			// getUnCompleteOrder();
			L.v("更新", "更新");
			L.v("get_data", "" + get_data.size());
			get_data.clear();
			// GetData();
			L.v("get_data", "" + get_data.size());
			SetDataToListView();
			// adapter.notifyDataSetChanged();
			// adapter.notifyDataSetInvalidated();
			L.v("更新完成", "更新完成");
			Refreash = false;
			app.new_home_activity_data_has_change = false;
		} else {
			SetDataToListView();
		}
	}

	private void StartWork() {
		// 一开始是不接单的
		// L.v("点击了", "-------1-------");
		//审核通过才行
		if ((app.userInfoBeen.getChecked().equals("0"))) {
			acceptOdrerShowDialog("您的个人信息未完善或者正在审核",0);
			Toast.makeText(this, "只有审核通过的司机能够承接我们的货物", Toast.LENGTH_LONG).show();
			return;
		}		
		if (app.userInfoBeen.getChecked().equals("2")) {
			acceptOdrerShowDialog("您的个人信息审核未能通过，请检查您填写的信息是否有误。",2);
			Toast.makeText(this, "您的个人信息审核未能通过，请检查您填写的信息。", Toast.LENGTH_LONG).show();
			return;
		}
//		L.e("连接状态","-->"+ JPushInterface.getConnectionState(getApplicationContext()));
		if (!JPushInterface.getConnectionState(getApplicationContext())) {
			JPushInterface.init(getApplicationContext());
			JPushInterface.resumePush(getApplicationContext());
		}
		if (JPushInterface.isPushStopped(getApplicationContext())) {
			JPushInterface.resumePush(getApplicationContext());
		}
		if (Is_Work_Flag) {
			// L.v("--------1------", "---------1--------");
			app.DriverIsOnline = false;
//			String off_messagepushuserid = app.messagepushuserId;
			String off_messagepushchannelId = app.channelId;
			if ((app.longitude != 0) && (app.latitude != 0)
					&& off_messagepushchannelId != null
//					&& off_messagepushuserid != null
					&& !(off_messagepushchannelId.equals(""))
					//&& !(off_messagepushuserid.equals(""))
					) {
				app.add(app.latitude, app.longitude, app.adrr, "off",
						off_messagepushchannelId, "null");
				Is_Work_Flag = true;
				// L.v("Is_Work_Flag", "" + Is_Work_Flag);
				// work_image.setBackgroundResource(R.drawable.start);
				work_image.startAnimation(work_image_animation);
				work_image_animation.cancel();
				showdriverstae.setBackgroundResource(R.drawable.souch_order);
				Is_Work_Flag = false;
			}
			// 不接单状态
		} else {
			// 点击了开始接单
			// L.v("------2--------", "-----------2------");
			// L.v("stop", "" + Is_Work_Flag);
			String messagepushuserid = app.messagepushuserId;
			String messagepushchannelId = app.channelId;
			app.DriverIsOnline = true;

			if ((app.longitude != 0) && (app.latitude != 0)
					&& messagepushchannelId != null
					&& messagepushuserid != null
					&& !(messagepushchannelId.equals(""))
				//	&& !(messagepushuserid.equals(""))
					) {
				app.add(app.latitude, app.longitude, app.adrr, "on",
						messagepushchannelId, messagepushuserid);
				Is_Work_Flag = true;
				// work_image.setBackgroundResource(R.drawable.stop);
				work_image.startAnimation(work_image_animation);
				showdriverstae.setBackgroundResource(R.drawable.searching);
			} else {

		//		Start_PushMessage();
				Toast.makeText(new_home_activity.this, "初始化中请等待2秒后再点击...",
						Toast.LENGTH_LONG).show();
				
			}
		}

	}

	private void OnListenerPushMessage() {

		app.SetPushMessageLister(new GetPushMessage() {

			@Override
			public void GetMessage(String msg, String CarTeamId,
					String CarTeamLeader) {
				// TODO Auto-generated method stub
				Refreash = true;
				L.v("sourceDateList", "" + sourceDateList.size());
				if (sourceDateList != null) {
					sourceDateList.clear();
					L.v("sourceDateList", "是空");
					L.v("sourceDateList", "" + sourceDateList.size());
				}
				getUnCompleteOrder();
				L.v("app", "回调函数");
			}
		});

	}

//	public void Start_PushMessage() {
//		PushManager.startWork(getApplicationContext(),
//				PushConstants.LOGIN_TYPE_API_KEY, "xGVLGuGeyehuEoNSxwRxFeEu");
//	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		switch (view.getId()) {
		case R.id.background:
			Intent intent = new Intent(this, new_home_activity.class);
			// startActivity(intent);
			StartWork();
			break;
		case R.id.workstart:
			Intent intent2 = new Intent(this, new_home_activity.class);
			// startActivity(intent2);
			StartWork();
			break;
		default:
			break;
		}
	}
	
	/**
	 * 
	* @Title: acceptOdrerShowDialog 
	* @Description: TODO(用户没有通过审核不能接单) 
	* @param @param messages  参数说明 
	* @return void    返回类型 
	* @throws
	 */
	private void acceptOdrerShowDialog(String messages,int type) {
		LayoutInflater inflater = LayoutInflater.from(new_home_activity.this);
		LinearLayout layout = (LinearLayout) inflater.inflate(
				R.layout.alert_dialog, null);
		final Dialog isExit = new AlertDialog.Builder(new_home_activity.this)
				.create();
		isExit.show();
		isExit.setContentView(layout);
		// 设置对话框标题
		TextView title = (TextView) layout.findViewById(R.id.title);
		TextView message = (TextView) layout.findViewById(R.id.message);
		title.setText("请注意");
		// 设置对话框消息
		message.setText(messages);
		Button check = (Button) layout.findViewById(R.id.check);
		Button giveup = (Button) layout.findViewById(R.id.giveup);
		check.setText("马上完善信息");
		giveup.setText("取消");
		check.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				isExit.dismiss();
				// updateImg();
				// return true;
				Intent intent=new Intent(new_home_activity.this,MessageActivity.class);
				startActivity(intent);
			}
		});
		giveup.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				isExit.dismiss();
				// return false;
			}
		});
	}
	
	/**
	 * 检查百度推送是否开启
	 */
//	private void checkBaiduPushEable(){
//		if (!(PushManager.isPushEnabled(getApplicationContext()))) {
//			PushManager.startWork(getApplicationContext(),
//					PushConstants.LOGIN_TYPE_API_KEY, "xGVLGuGeyehuEoNSxwRxFeEu");
//
//			L.e("百度推送没有启动", "百度推送没有启动");
//		}else {
//			L.e("百度推送已经启动", "百度推送已经启动");
//			PushManager.startWork(getApplicationContext(),
//					PushConstants.LOGIN_TYPE_API_KEY, "xGVLGuGeyehuEoNSxwRxFeEu");
//
//		}		
//	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 开启菜单手势功能
		app.startMenuShowFunction();
		if (app.new_home_activity_data_has_change) {
			getUnCompleteOrder();
			app.new_home_activity_data_has_change=false;
		}
	//	offline();
	}

	@Override
	protected void onRestart() {
		// TODO Auto-generated method stub
		super.onRestart();
		// 开启菜单手势功能
		app.startMenuShowFunction();

		if (app.new_home_activity_data_has_change) {
			Refreash = true;
			// L.v("sourceDateList", ""+sourceDateList.size());
			if (sourceDateList != null) {
				sourceDateList.clear();
			//	L.v("sourceDateList", "是空");
			//	L.v("sourceDateList", "" + sourceDateList.size());
			}
			getUnCompleteOrder();
		//	L.v("app", "回调函数");
			app.new_home_activity_data_has_change=false;
		}
		L.v("onPause", "onPause");
		if (app.Have_Order_Complete) {
			// SetOrderNumber();
			getUnCompleteOrder();
		}
//		checkBaiduPushEable();
	}

//	

	
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		// 停止手势功能
		app.stopMenuShowFunction();
//		checkBaiduPushEable();
	}
	
	
	@Override
	protected void onRestoreInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(outState);
		LocationClient mLocationClient = app.mLocationClient;
		mLocationClient.stop();
		app.DriverIsOnline = false;
		app.add(app.latitude, app.longitude, app.adrr, "off",
				app.messagepushuserId, app.channelId);
		L.e(app.latitude+"", app.longitude+"");
//		PushManager.stopWork(getApplicationContext());
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
	
		LocationClient mLocationClient = app.mLocationClient;
		mLocationClient.stop();
		app.DriverIsOnline = false;
	
	//	Intent intent = new Intent();  
      //   intent.setAction("com.wonyesoft.wuliu.driver");  
	//	intent.setAction("下线了");  
      //   L.v("发送广播", "发送广播");
	//	new_home_activity.this.sendBroadcast(intent);  
		
//		HashMap< String, Object> dataMap=new HashMap<String, Object>();
		app.add(app.latitude, app.longitude, app.adrr, "off",
				app.messagepushuserId, app.channelId);	
//		offline();
//		dataMap.put("latitude", app.latitude);
//		dataMap.put("longitude", app.longitude);
//		dataMap.put("address", app.adrr);
//		dataMap.put("userId", "null");
//		dataMap.put("userId", app.messagepushuserId);
//		dataMap.put("channelId", app.channelId);
//		dataMap.put("carownerId", app.userId);
//		L.v("被结束", "被结束");
//		Intent intent=new Intent(this,OfflineService.class);
//		Gson gson=new Gson();		
//		String json_str=gson.toJson(dataMap);
//		L.v("json_str", json_str);
//		intent.putExtra("data", json_str);
//		L.v("启动成功", "启动成功");
//		startService(intent);
//		L.v("启动成功", "启动成功");
		super.onDestroy();
	}
	
	private void offline(){
		HashMap< String, Object> dataMap=new HashMap<String, Object>();
		dataMap.put("latitude", app.latitude);
		dataMap.put("longitude", app.longitude);
		dataMap.put("address", app.adrr);
		dataMap.put("userId", "null");
		dataMap.put("userId", app.messagepushuserId);
		dataMap.put("channelId", app.channelId);
		dataMap.put("carownerId", app.userId);
		L.v("被结束", "被结束");
	//	Intent intent=new Intent(this,OfflineService.class);
	//	OffLineData offLineData=new OffLineData();
	//	offLineData.setCookie(app.preferencesCookieStore);
		Gson gson=new Gson();		
		String json_str=gson.toJson(dataMap);
	//	offLineData.setJson_str(json_str);
		//intent.putExtra("data", json_str);
	//	L.v("启动成功", "启动成功");
	//	startService(intent);
	}
	
}
